package com.book.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.common.utils.DateUtils;
import com.book.common.utils.SecurityUtils;
import com.book.system.domain.Book;
import com.book.system.domain.BookChapter;
import com.book.system.mapper.BookMapper;
import com.book.system.service.IBookChapterService;
import com.book.system.service.IBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Bigboss
 * @create 2024-10-19 20:58
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    private final BookMapper bookMapper;
    private final IBookChapterService bookChapterService;

    public BookServiceImpl(BookMapper bookMapper, IBookChapterService bookChapterService) {
        this.bookMapper = bookMapper;
        this.bookChapterService = bookChapterService;
    }

    /**
     * 更新书籍章节
     * @param chapter
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addChapter(BookChapter chapter) {
        boolean bool = bookChapterService.save(chapter);
        if(bool){
            //更新书籍信息表中目前章节数量
            Book book = new Book();
            book.setId(chapter.getBookId());
            book.setChapter(chapter.getChapter());
            book.setUpdateBy(SecurityUtils.getUsername());
            book.setUpdateTime(DateUtils.getNowDate());
            bookMapper.updateById(book);
        }
        return bool;
    }

    /**
     * 获取书籍章节
     * @param bookId
     * @return
     */
    @Override
    public List<BookChapter> getAllChapters(String bookId) {
        return bookChapterService.list(new LambdaQueryWrapper<BookChapter>().eq(BookChapter::getBookId,bookId));
    }
}
